package aaaClicker;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.annotation.security.RunAs;

import org.eclipse.swt.widgets.Display;

import com.attilax.core;

public class FutureTaskAti<T> implements Future {

	public FutureTaskAti(Runnable runnable, ResultObject object) {
		new Thread(runnable).start();
		countTime();
		this.result=object;
	}

	public ResultObject result;

	private void countTime() {

		core.execMeth_Ays(new Runnable() {

			@Override
			public void run() {
				while (true) {

					// Thread.yield();
					// System.out.println("--is true");
					//
					// System.out.println("111");

					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					timePassNow = timePassNow + 500;

					// System.out.println(" busy single busy2");

				}

			}
		}, "");

	}

	@Override
	public boolean cancel(boolean mayInterruptIfRunning) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isCancelled() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isDone() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Object get() throws InterruptedException, ExecutionException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * while (true) { if (busy_single) { // Thread.yield();
	 * System.out.println("--is true");
	 * 
	 * 
	 * System.out.println("111"); display.syncExec(new Runnable() {
	 * 
	 * @Override public void run() { if (!display.readAndDispatch()) {
	 *           System.out.println("222"); display.sleep(); }
	 * 
	 *           } });
	 * 
	 * 
	 *           // }); // Thread.sleep(5000);
	 * 
	 *           System.out.println(" busy single busy2"); } else break; }
	 */
	long timePassNow = 0;

	@Override
	public Object get(long timeout, TimeUnit unit) throws InterruptedException,
			ExecutionException, TimeoutException {
		while (true) {

			// Thread.yield();
			// System.out.println("--is true");
			//
			// System.out.println("111");

			if (result.rzt!= null)
				return result.rzt;
			else {
				if (timePassNow > timeout * 1000)
					throw new TimeoutException();
				final Display default1 = Display.getDefault();
				default1.syncExec(new Runnable() {
					// //
					@Override
					public void run() {
						if (!default1.readAndDispatch()) {
						 	System.out.println("222a");
							default1.sleep();
						}

					}
				});
				// Thread.sleep(500);
			}

			// System.out.println(" busy single busy2");

		}
	}

}
